/*
 * Implementation for the mbed library
 * https://github.com/mbedmicro/mbed
 *
 * Copyright (c) 2016-2019 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "events/internal/equeue_platform.h"

#if defined(EQUEUE_PLATFORM_FREERTOS)

#include <stdbool.h>
#include <string.h>
#include "cmsis.h"
#include "mbed_critical.h"


// Ticker operations
void equeue_tick_init(void)
{
}

unsigned equeue_tick(void)
{
	return (unsigned)xTaskGetTickCount();
}

// Mutex operations
int equeue_mutex_create(equeue_mutex_t *m)
{
    return 0;
}
void equeue_mutex_destroy(equeue_mutex_t *m) { }

void equeue_mutex_lock(equeue_mutex_t *m)
{
    core_util_critical_section_enter();
}

void equeue_mutex_unlock(equeue_mutex_t *m)
{
    core_util_critical_section_exit();
}


// Semaphore operations


int equeue_sema_create(equeue_sema_t *s)
{
	*s = xSemaphoreCreateBinary();
    return 0;
}

void equeue_sema_destroy(equeue_sema_t *s)
{
	vSemaphoreDelete(*s);
}

void equeue_sema_signal(equeue_sema_t *s)
{
	if(core_util_is_isr_active()){
		static BaseType_t xHigherPriorityTaskWoken;
		xSemaphoreGiveFromISR(*s, &xHigherPriorityTaskWoken);
	}
	else{
		xSemaphoreGive(*s);
	}
}

bool equeue_sema_wait(equeue_sema_t *s, int ms)
{
	TickType_t ticks;
	
    if (ms < 0) {
        ticks = portMAX_DELAY;
    }
	else{
		ticks = portTICK_PERIOD_MS(ms);
	}
	
    return xSemaphoreTake(*s, ticks) == pdTRUE;
}


#endif
